package com.gainloop.Listeners;

import java.util.ArrayList;

import org.alexd.jsonrpc.JSONRPCException;

import com.gainloop.Api.Tags;
import com.gainloop.Api.Entity.Tag;

import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.widget.ArrayAdapter;

/**
 * This class will be used for adding auto complete ability to the Tags section. 
 * @author Meir
 *
 */
public class TagsTextWatcher implements TextWatcher{
	
	private ArrayAdapter<String> _tagsAdapter;
	
	public TagsTextWatcher(ArrayAdapter<String> tagsAdapter){
		_tagsAdapter = tagsAdapter;
	}
	@Override
	public void afterTextChanged(Editable arg0) {}

	@Override
	public void beforeTextChanged(CharSequence arg0, int arg1,
			int arg2, int arg3) {}

	@Override
	public void onTextChanged(CharSequence s, int start, int before, int count) {
		_tagsAdapter.clear();
		if(s.length()==0){
			 return;
		}
		Tags tags = new Tags();
		ArrayList<Tag> foundTags = null;
		try {
			foundTags = tags.findTags(s.toString());
		} catch (JSONRPCException e) {
			Log.v("Tags server","Error");
			e.printStackTrace();
			return;
		}
		
		if(foundTags!=null){
            for (Tag curTag:foundTags){
            	_tagsAdapter.add(curTag.getName());
            }
		}
	}

}
